package exteditapp;

import java.util.ArrayList;

import exteditapp.command.ICommand;

/**
 * Operation invoker.
 * @author Arturas Smorgun, arturas@smorgun.lt
 */
public class Invoker {

	protected ArrayList<ICommand> commands4execution = new ArrayList<ICommand>();
	
	protected Thread currentCommand = null;
	
	protected boolean executing = false;
	
	/**
	 * Default constructor
	 */
	public Invoker(){}

	/**
	 * Execute command by given action string and file state
	 * @param caller File, on which will be done operation
	 * @param commandLine any commands for execute
	 * @return true on immediate execution and false if placed in queue
	 */
	public synchronized Boolean execute(ICommand command) {
		System.out.println("NEW EXECUTE  "+command.toString());
		if(executing == false){
			setExecution(true);
			new Thread(command).start();
			return true;
		}
		commands4execution.add(command);
		return false;
	}
	
	public synchronized boolean setExecution(boolean state){
		if(executing == true && state == false){
			if(commands4execution.size() > 0){
				ICommand command = commands4execution.get(0);
				commands4execution.remove(0);
				currentCommand = new Thread(command);
				currentCommand.start();
				return false;
			}
			else{
				executing = false;
				currentCommand = null;
			}
		}
		else if(executing == false && state == true){
			executing = true;
		}
		else{
			return false;
		}
		return true;
	}
	
	public synchronized boolean getExecution(){
		return executing;
	}
	
	public synchronized void interrupExecutions(){
		if(currentCommand != null)
			currentCommand.interrupt();
		this.commands4execution.clear();
	}
	
}
